package com.ky.manage.fragment;

import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ky.manage.R;
import com.ky.manage.adapter.MyOrderAdapter;
import com.ky.manage.base.BaseFragment;
import com.ky.manage.model.response.OrderResp;
import com.ky.manage.ui.RecycleViewDivider;
import com.ky.manage.ui.dialog.CommonDialog;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cz.msebera.android.httpclient.Header;

public class OrderFragment extends BaseFragment implements MyOrderAdapter.Order2PayListner {

    private RefreshLayout refreshLayout;
    private ImageView mToTopIv;
    private RecyclerView recyclerView;
    int type = 0;//0 全部订单  1 待付款  2待评论
    List<OrderResp.RowsDTO> dataList = new ArrayList<>();
    MyOrderAdapter adapter;

    public OrderFragment(int type) {
        this.type = type;
    }

    @Override
    protected int layoutId() {
        return R.layout.layout_home_tab_fragment;
    }

    @Override
    protected void initView(View rootView) {
        mToTopIv = findView(R.id.to_top_iv, v -> {
            //置顶
            recyclerView.smoothScrollToPosition(0);
            mToTopIv.setVisibility(View.GONE);
        });
        recyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.VERTICAL,
                ScreenUtils.dp2px(10), mContext.getColor(R.color.gray_light)));
    }

    @Override
    protected void initData() {

        reqOrderList();
    }

    private void reqOrderList() {
        String param = "";
        switch (type) {
            case 1:
                param = "/appApi/getOrderList?orderStatus=2";
                break;
            case 2:
                param = "/appApi/getOrderList?orderStatus=4";
                break;
            default:
                param = "/appApi/getOrderList";
                break;
        }
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + param, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "reqOrderList onFailure = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "reqOrderList onSuccess = " + responseString);
                OrderResp orderResp = new Gson().fromJson(responseString, OrderResp.class);
                if(orderResp != null && orderResp.getCode() == 200) {
                    dataList =  orderResp.getRows();
                    adapter = new MyOrderAdapter(getContext(),R.layout.item_my_order, dataList, OrderFragment.this);
                    //adapter.setNewList(dataList);
                    recyclerView.setAdapter(adapter);
                }
            }
        });
    }


    CommonDialog payDialog;

    private void showAddPicDialog(String qrcode, String orderCode) {

        if (null == payDialog) {
            WeakReference<Fragment> activityWeakReference = new WeakReference<>(this);
            payDialog = CommonDialog.create(activityWeakReference.get().getFragmentManager())
                    .setLayoutRes(R.layout.dialog_pay)
                    .setViewListener(((v, baseDialog) -> {
                        if (null == activityWeakReference || null == activityWeakReference.get()
                                || activityWeakReference.get().isRemoving()) {
                            return;
                        }
                        TextView payCancel = v.findViewById(R.id.tv_pay_cancel);
                        TextView payDone = v.findViewById(R.id.tv_pay_done);
                        ImageView ivQrCode = v.findViewById(R.id.qr_code);
                        ivQrCode.setImageBitmap(CodeUtils.createImage(qrcode, 400, 400, null));
                        payDone.setOnClickListener(v1 -> {
                            //支付完成   查询订单状态
                            reqOrderStatus(orderCode);

                        });
                        payCancel.setOnClickListener(v1 -> {
                            //关闭弹框
                            hidePayDialog();
                        });
                    }))
                    .setDialogAnimationRes(R.style.Center_Zoom_Dialog)
                    .setGravity(Gravity.CENTER)
                    .setOnDismissListener(dialog -> {
                        //对话框关闭
                        hidePayDialog();
                    })
                    .setDialogWidth(ScreenUtils.dp2px(300))
                    .setDimAmount(0.2f)
                    .setCancelOutside(false)
                    .setKeyBackDismiss(false)
                    .setTag("AddPicDialog");
        }

        if (payDialog.isShowing()) {
            return;
        }
        payDialog.show();
    }

    private void hidePayDialog() {
        if (null != payDialog) {
            payDialog.dismissAllowingStateLoss();
            payDialog = null;
        }
    }

    @Override
    public void OnOrder2Pay(String qrCode, String orderCode) {
        showAddPicDialog(qrCode, orderCode);
    }

    private void reqOrderStatus(String orderCode) {
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/queryOrderStatus?orderCode=" + orderCode, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "reqOrderStatus onFailure = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "reqOrderStatus onSuccess = " + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if(jsonObject != null && jsonObject.has("code")) {

                        if(jsonObject.getInt("code") == 500) {
                            ToastUtils.showToast(jsonObject.getString("msg"));
                        } else if(jsonObject.getInt("code") == 200) {
                            ToastUtils.showToast(jsonObject.getString("msg"));
                            hidePayDialog();
                            reqCloseOrder(orderCode);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void reqCloseOrder(String orderCode) {
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/closeOrder?orderCode=" + orderCode, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "reqCloseOrder onFailure = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "reqCloseOrder onSuccess = " + responseString);
            }
        });
    }
}
